package com.zenghm.demo;

import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LiveData;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.zenghm.demo.databinding.ActivityMainBinding;
import com.zenghm.retrofit2.adapter.LiveDataCallAdapterFactory;
import com.zenghm.retrofit2.adapter.SafeLiveData;

import java.util.Map;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.apiopen.top/api/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(LiveDataCallAdapterFactory.create())
                .build();
        SentencesApi sentencesApi = retrofit.create(SentencesApi.class);

        LiveData<JsonObject> liveData = sentencesApi.get();
        liveData.observe(this, body -> {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, JsonElement> entry : body.entrySet()) {
                sb.append(entry.getKey()).append(": ").append(entry.getValue())
                        .append(System.lineSeparator());
            }
            binding.textview.setText(sb);
        });
        if (liveData instanceof SafeLiveData) {
            ((SafeLiveData<JsonObject>) liveData).error().observe(this, throwable ->
                    Toast.makeText(MainActivity.this, throwable.getMessage(), Toast.LENGTH_SHORT).show());
        }
    }
}